package com.cj.bus.controller;


import java.io.File;
import java.time.LocalDateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.cj.bus.common.entity.ResponseEntity;
import com.cj.bus.common.entity.ResponseHelper;
import com.cj.bus.common.utils.FileUtil;
import com.cj.bus.entity.BusAccessoryEntity;
import com.cj.bus.service.BusAccessoryService;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/push")
@Validated
@Api(tags = {"附件相关接口"})
@Slf4j
public class BusAccessoryController {

	@Autowired private BusAccessoryService busAccessoryService;
	
	@Value("${front.profile}")
	private String filePath;
	
	@PostMapping("fileUpload")
	@ResponseBody
	public ResponseEntity<BusAccessoryEntity> fileUpload(@RequestParam("file") MultipartFile file){		
		if (file.isEmpty()) {			
            return ResponseHelper.failServerError("文件为空");
        }else{
          	 String fileName = file.getOriginalFilename();
          	int index = fileName.lastIndexOf(".");
          	 String fileSuffix = fileName.substring(index);
          	 
        	File targetFile = FileUtil.saveFile(file, filePath);
            BusAccessoryEntity busAccessoryEntity = new BusAccessoryEntity();
            busAccessoryEntity.setAccessoryName(fileName);
            busAccessoryEntity.setAccessoryType(fileSuffix);
            busAccessoryEntity.setAddress(targetFile.getAbsolutePath().replace(filePath, ""));
            busAccessoryEntity.setCreateTime(LocalDateTime.now());
            busAccessoryEntity.setSize(file.getSize()/1.0);
            //入库
            busAccessoryService.save(busAccessoryEntity);
            return ResponseHelper.success(busAccessoryEntity);
        }
		
	}
	
	public static void main(String[] args) {
		File file = new File("/Users/yanghao0518/Downloads/万科工作总结/朴寓/源码/airhome/airhome-business/src/main/java/com/vanke/airhome/common/util/RequestUtils.java");
		String fileName = file.getName();
      	int index = fileName.lastIndexOf(".");
      	 String fileSuffix = fileName.substring(index);
      	 System.out.println(fileName);
      	System.out.println(fileSuffix);
      	System.out.println(file.getAbsolutePath());
	}


}
